<script setup lang="ts">
import { onMounted, ref } from 'vue'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import DayView from './DayView.vue'
import WeekView from './WeekView.vue'
import MonthView from './MonthView.vue'
import AddRecord from './AddRecord.vue'
import { type AccountBookQueryDTO, FinanceService } from '/@/api/openapi'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Record {
  id: number
  name: string
  type: string
  category: string
  date: string
  amount: number
  remark?: string
}

// 模拟数据
const records = ref<Record[]>([])

onMounted(() => {
  // 默认加载最近两个月的数据
  query.value.startTime = defaultDateRange()[0].toISOString().slice(0, 10)
  query.value.endTime = defaultDateRange()[1].toISOString().slice(0, 10)
  loadData()
})

const query = ref<AccountBookQueryDTO>({
  pageNum: 1,
  pageSize: 1000,
  startTime: '',
  endTime: ''
})

const defaultDateRange = () => {
  const now = new Date()
  const end = new Date() // 当月最后一天
  const start = new Date(now.getFullYear(), now.getMonth() - 1, 1) // 上月第一天
  console.log('startDate:', start, 'endDate:', end)
  return [start, end]
}
// 调用 FinanceService.list 方法获取数据
const loadData = async () => {
  console.log('记账本正在查询')
  FinanceService.list(query.value).then(res => {
    console.log('返回结果')
    console.log(res)
    const data = res.data?.records || []
    records.value = data
      .map(item => {
        if (!item) return null
        return {
          id: item.id || 0,
          name: item.name || '',
          type: item.type === 1 ? '收入' : '支出',
          category: item.category || '',
          date: (item.date || '').slice(0, 10),
          amount: item.amount || 0,
          remark: item.remark || '',
        }
      })
      .filter(Boolean) as Record[]
  })
}

const showAddForm = ref<{ [key: string]: boolean }>({})
const viewMode = ref<'day' | 'week' | 'month'>('day')

const toggleAddForm = (date: string) => {
  showAddForm.value[date] = !showAddForm.value[date]
}

const handleAddSuccess = async (newRecord: Omit<Record, 'id'>) => {
  // records.value.push({
  //   ...newRecord,
  //   id: records.value.length + 1,
  // })
  // 这里调用FinanceService.save方法
  await FinanceService.add1({
    name: newRecord.name,
    type: newRecord.type === '收入' ? 1 : 2,
    category: newRecord.category,
    date: newRecord.date,
    amount: newRecord.amount,
    remark: newRecord.remark,
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success(res.message)
    } else {
      ElMessage.error(res.message)
    }
  })
  await loadData();
  // 新增记录后关闭表单
  // showAddForm.value[newRecord.date] = false
}

// 更新记录的表单数据
const updateForm = ref<Record | null>(null)
const updateDialogVisible = ref(false)

// 打开更新对话框
const openUpdateDialog = (record: Record) => {
  updateForm.value = { ...record } // 复制一份数据，避免直接修改原数据
  updateDialogVisible.value = true
}

// 确认更新
const confirmUpdate = async () => {
  if (!updateForm.value) return

  try {
    await FinanceService.update({
      id: updateForm.value.id,
      name: updateForm.value.name,
      type: updateForm.value.type === '收入' ? 1 : 2,
      category: updateForm.value.category,
      date: updateForm.value.date,
      amount: updateForm.value.amount,
      remark: updateForm.value.remark,
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success(res.message)
      } else {
        ElMessage.error(res.message)
      }
    })

    // 更新成功后重新加载数据
    await loadData()
    updateDialogVisible.value = false
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新记录失败:', error)
    ElMessage.error('更新失败，请重试')
  }
}

// 处理更新记录
const handleUpdateRecord = async (record: Record) => {
  openUpdateDialog(record)
}

// 处理删除记录
const handleDeleteRecord = async (record: Record) => {
  try {
    await FinanceService.delete1({
      ids: [record.id],
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success(res.message)
      } else {
        ElMessage.error(res.message)
      }
    })

    // 删除成功后重新加载数据
    await loadData()
  } catch (error) {
    console.error('删除记录失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 导出Excel功能
const exportToExcel = () => {
  // 准备导出数据
  const exportData = records.value.map(record => ({
    日期: record.date,
    名称: record.name,
    类型: record.type,
    金额: record.amount,
    收支: record.type === '收入' ? '收入' : '支出',
  }))

  // 创建工作簿
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(exportData)

  // 设置列宽
  const colWidths = [
    { wch: 12 }, // 日期
    { wch: 20 }, // 名称
    { wch: 8 }, // 类型
    { wch: 12 }, // 金额
    { wch: 8 }, // 收支
  ]
  ws['!cols'] = colWidths

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '记账记录')

  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([excelBuffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  })
  saveAs(blob, `记账记录_${new Date().toLocaleDateString()}.xlsx`)
}

// 处理日期范围变化
const handleDateRangeChange = ({ startDate, endDate }: { startDate: string; endDate: string }) => {
  query.value.startTime = startDate
  query.value.endTime = endDate
  loadData()
}
</script>

<template>
  <div class="page-container">
    <div class="record-list">
      <div class="control-bar">
        <div class="view-controls">
          <button
            :class="['view-button', { active: viewMode === 'day' }]"
            @click="viewMode = 'day'"
          >
            按天查看
          </button>
          <button
            :class="['view-button', { active: viewMode === 'week' }]"
            @click="viewMode = 'week'"
          >
            按周查看
          </button>
          <button
            :class="['view-button', { active: viewMode === 'month' }]"
            @click="viewMode = 'month'"
          >
            按月查看
          </button>
          <button class="view-button" @click="loadData">
            <i class="fa fa-sync-alt"></i> 刷新(需要登陆,不然数据为空)
          </button>
        </div>
        <button class="export-button" @click="exportToExcel">
          <i class="fa fa-file-excel"></i> 导出Excel
        </button>
      </div>

      <DayView
        v-if="viewMode === 'day'"
        :records="records"
        :start-time="query.startTime"
        :end-time="query.endTime"
        :show-add-form="showAddForm"
        @toggle-add-form="toggleAddForm"
        @add-success="handleAddSuccess"
        @update-record="handleUpdateRecord"
        @delete-record="handleDeleteRecord"
        @date-range-change="handleDateRangeChange"
      />

      <WeekView
        v-else-if="viewMode === 'week'"
        :records="records"
        :start-date="query.startTime"
        :end-date="query.endTime"
        :show-add-form="showAddForm"
        @toggle-add-form="toggleAddForm"
        @add-success="handleAddSuccess"
      />

      <MonthView
        v-else
        :records="records"
        :show-add-form="showAddForm"
        @toggle-add-form="toggleAddForm"
        @add-success="handleAddSuccess"
      />
    </div>

    <!-- 更新记录对话框 -->
    <el-dialog v-model="updateDialogVisible" title="更新记录" width="500px">
      <el-form v-if="updateForm" :model="updateForm" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="updateForm.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="类型">
          <el-select v-model="updateForm.type" placeholder="请选择类型">
            <el-option label="收入" value="收入" />
            <el-option label="支出" value="支出" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类">
          <el-input v-model="updateForm.category" placeholder="请输入分类" />
        </el-form-item>

        <el-form-item label="日期">
          <el-date-picker
            v-model="updateForm.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="金额">
          <el-input-number
            v-model="updateForm.amount"
            :precision="2"
            :step="100"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="updateForm.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-container {
  display: flex;
  justify-content: center;
  padding: 24px;
}

.record-list {
  width: 70%;
  max-width: 1200px;
}

.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.view-controls {
  display: flex;
  gap: 16px;
}

.view-button {
  padding: 8px 16px;
  border: 1px solid #1890ff;
  border-radius: 4px;
  background: white;
  color: #1890ff;
  cursor: pointer;
  transition: all 0.3s;
}

.view-button.active {
  background: #1890ff;
  color: white;
}

.view-button:hover {
  opacity: 0.8;
}

.export-button {
  padding: 8px 16px;
  background: #52c41a;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background-color 0.3s;
}

.export-button:hover {
  background: #73d13d;
}

.export-button i {
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
